﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;
using ERP_SaaS_WinForm.物料管理.Material;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net;

namespace ERP_SaaS_WinForm.物料管理
{
    public partial class ProcessInspectionForm : CCSkinMain
    {
        public ProcessInspectionForm()
        {
            InitializeComponent();
            this.Load += ProcessInspectionForm_Load;
            InitializeGrid();
        }

        private async void ProcessInspectionForm_Load(object sender, EventArgs e)
        {
            await QueryAndBindAsync();
        }

        private async void btnProcessSearch_Click(object sender, EventArgs e)
        {
            await QueryAndBindAsync();
        }

        /// <summary>
        /// 查询并绑定过程质检数据
        /// </summary>
        private async Task QueryAndBindAsync()
        {
            string baseUrl = "http://localhost:5128/api/ProcessInspection/GetProcessInspection";
            string inspectionOrderCode = txtMaterialCode != null ? txtMaterialCode.Text?.Trim() : string.Empty;
            
            // 如果有搜索条件，添加到URL中
            if (!string.IsNullOrEmpty(inspectionOrderCode))
            {
                baseUrl += $"?inspectionOrderCode={Uri.EscapeDataString(inspectionOrderCode)}";
            }

            using (HttpClient client = new HttpClient())
            {
                try
                {
                    HttpResponseMessage response = await client.GetAsync(baseUrl);
                    response.EnsureSuccessStatusCode();
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    
                    // 使用MaterialApiResponse<T>反序列化API响应
                    var apiResponse = JsonConvert.DeserializeObject<MaterialApiResponse<ProcessInspectionDto>>(jsonResponse);
                    
                    if (apiResponse != null && apiResponse.code == 200)
                    {
                        var list = apiResponse.data;
                        if (list != null && list.Count > 0)
                        {
                            // 绑定数据到DataGridView
                            dgvProcessInspection.AutoGenerateColumns = false;
                            dgvProcessInspection.DataSource = list;
                        }
                        else
                        {
                            dgvProcessInspection.DataSource = null;
                            MessageBox.Show("未找到相关数据");
                        }
                    }
                    else
                    {
                        MessageBox.Show($"查询失败: {apiResponse?.message ?? "未知错误"}");
                        dgvProcessInspection.DataSource = null;
                    }
                }
                catch (HttpRequestException ex)
                {
                    MessageBox.Show($"网络请求失败: {ex.Message}");
                    dgvProcessInspection.DataSource = null;
                }
                catch (JsonException ex)
                {
                    MessageBox.Show($"数据解析失败: {ex.Message}");
                    dgvProcessInspection.DataSource = null;
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"操作失败: {ex.Message}");
                    dgvProcessInspection.DataSource = null;
                }
            }
        }

        /// <summary>
        /// 初始化DataGridView
        /// </summary>
        private void InitializeGrid()
        {
            // 设置DataGridView属性
            dgvProcessInspection.AutoGenerateColumns = false;
            dgvProcessInspection.AllowUserToAddRows = false;
            dgvProcessInspection.AllowUserToDeleteRows = false;
            dgvProcessInspection.ReadOnly = true;
            dgvProcessInspection.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvProcessInspection.MultiSelect = false;
            
            // 绑定单元格格式化事件
            dgvProcessInspection.CellFormatting += DgvProcessInspection_CellFormatting;
            
            // 绑定搜索按钮事件
            if (btnProcessSearch != null)
            {
                btnProcessSearch.Click -= btnProcessSearch_Click;
                btnProcessSearch.Click += btnProcessSearch_Click;
            }
        }

        /// <summary>
        /// 处理单元格格式化
        /// </summary>
        private void DgvProcessInspection_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == 12 && e.Value != null) // 检验结果列
            {
                if (bool.TryParse(e.Value.ToString(), out bool state))
                {
                    e.Value = state ? "合格" : "不合格";
                    e.FormattingApplied = true;
                }
            }
            else if (e.ColumnIndex == 7 && e.Value != null) // 检验日期列
            {
                if (DateTime.TryParse(e.Value.ToString(), out DateTime date))
                {
                    e.Value = date.ToString("yyyy-MM-dd HH:mm:ss");
                    e.FormattingApplied = true;
                }
            }
        }
        /// <summary>
        /// 刷新数据
        /// </summary>
        public async Task RefreshDataAsync()
        {
            await QueryAndBindAsync();
        }

        private void ProcessInspectionForm_Load_1(object sender, EventArgs e)
        {

        }
    }
}
